import React from 'react';
import Taro from '@tarojs/taro';

import { connect } from 'react-redux';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import ReceivingCodeInput from '@/pages/common/receiving-code-input/receiving-code';
import { AtActionSheet, AtTextarea, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui';
import 'taro-ui/dist/style/components/textarea.scss';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/modal.scss';
import { View, Text, Image, Button, ScrollView } from '@tarojs/components';
import ReleasedTab from './components/ReleasedTab'; //我的发布订单tab
import ReceivingTab from './components/ReceivingTab'; //我的接单订单tab
import OrderItem from './components/OrderItem'; //订单item
import './index.less';
import kf from './img/kf.png';
import close from './img/close.png';
import checkIcon from '@/assets/image/community/c_check.png';
import checkedIcon from '@/assets/image/community/c_checked.png';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class LifeOrdersD extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      paySelected: 0,
      list: [
        {
          label: '临时有事，我不想取了',
        },
        {
          label: '等待太久无人接单',
        },
        {
          label: '订单信息填写有误',
        },
        {
          label: '其他',
        },
      ],
      value: '',
    };
  }

  componentDidMount() {
    let {
      actions: { action },
    } = this.props;
    let { orderType } = Taro.getCurrentInstance()?.router?.params;
    action.commonChange('main.orderType', Number(orderType));
  }

  componentDidShow() {
    this.props.actions.init()
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  // async hkClick() {
  //   let itemStr = Taro.getStorageSync('b2b-wechat@login');
  //   if (!itemStr) {
  //     Taro.navigateTo({
  //       url: '/pages/package-C/login/login/index',
  //     });
  //     return;
  //   }
  //   Taro.setStorageSync('url', 'https://www.daoway.cn/h5/allorder.html?channel=rykj');
  //   Taro.navigateTo({
  //     url: '/pages/package-A/webview/index',
  //   });
  // }

  _onScrollToLower = () => {
    let {
      main: { pageNum, totalPages, orderType },
      actions: { action },
    } = this.props;
    let num = pageNum + 1;
    if (num > totalPages) return;
    action.commonChange('main.pageNum', num);
    if (orderType === 1) {
      action.findMyEscorttradeList();
    } else {
      action.findEscortsnatchorderList();
    }
  };

  _onRefresherRefresh = () => {
    let {
      main: { orderType },
      actions: { action },
    } = this.props;
    const { refresherTriggered } = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    action.commonChange('main.pageNum', 0);
    if (orderType === 1) {
      action.findMyEscorttradeList();
    } else {
      action.findEscortsnatchorderList();
    }
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  async kfClick() {
    let { enterpriseId, serviceLink } = Taro.getStorageSync('serviceonline')
    Taro.openCustomerServiceChat({
      extInfo: { url: serviceLink },
      corpId: enterpriseId,
    });
  }

  async checkClick(type, key) {
    let { list } = this.state;
    list.map((item, index) => {
      item.check = false;
      if (key === index) {
        item.check = true;
      }
    });
    this.setState({ list: list });
  }

  render() {
    let { refresherTriggered, list, value, paySelected } = this.state;
    if (!this.props.main) return null;
    let {
      main: {
        isLoading,
        isReady,
        payModel,
        cancelModel,
        confirmModel,
        orderType,
        orderList,
        pageNum,
        totalPages,
        harvestCode,
        cancellationReason,
        cancellationOptions,
        price,
        accountBalanceTotal,
        escortTradeStatus,
        escortSnatchOrderStatus
      },
      actions: { action },
    } = this.props;

    return (
      <View className="pageLifeOrdersD">
        <View className="title">
          <View className="take">代取服务</View>
          {/* <View className="hk" onClick={() => this.hkClick()}>
            家政服务
          </View> */}
        </View>
        <View className="tab">
          <Text
            className={orderType === 1 ? 'tab-item-x' : 'tab-item'}
            onClick={() => {
              action.commonChange('main.escortTradeStatus', null);
              action.commonChange('main.pageNum', 0);
              action.commonChange('main.pageSize', 10);
              action.commonChange('main.orderType', 1);
              action.findMyEscorttradeList();
            }}
          >
            我的发布
          </Text>
          <Text
            className={orderType === 2 ? 'tab-item-x' : 'tab-item'}
            onClick={() => {
              action.commonChange('main.escortSnatchOrderStatus', null);
              action.commonChange('main.pageNum', 0);
              action.commonChange('main.pageSize', 10);
              action.commonChange('main.orderType', 2);
              action.findEscortsnatchorderList();
            }}
          >
            我的接单
          </Text>
        </View>
        {orderType === 1 && <ReleasedTab />}
        {orderType === 2 && <ReceivingTab />}
        {/*订单数据*/}
        <ScrollView
          className="scroll"
          scrollY
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
        >
          {orderList && orderList.length > 0 ? (
            <View>
              {orderList.map((order, index) => {
                return (
                  <View key={index}>
                    <OrderItem order={order} orderType={orderType} />
                  </View>
                );
              })}
              {orderList.length != 0 && orderList.length > 3 && pageNum != totalPages && (
                <View className="status">加载中</View>
              )}
              {orderList.length != 0 && pageNum == totalPages && <View className="status">没有更多了</View>}
            </View>
          ) : (
            <View className="not-orders-list">
              {orderType === 1 ? (
                <>
                  <Image src={require('./img/order_null1.png')} className="current-none-img" mode="widthFix" />
                  <Text className="current-none-text">{escortTradeStatus === null ? '您还没发布过跑腿需求哦～' : '暂无订单数据'}</Text>
                  {escortTradeStatus === null && (
                    <View
                      className="orders-btn"
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.navigateTo({
                          url: '/pages/package-D/addPickupCourier/index',
                        });
                      }}
                    >
                      去发布
                    </View>
                  )}
                </>
              ) : (
                <>
                  <Image src={require('./img/order_null2.png')} className="current-none-img" mode="widthFix" />
                  <Text className="current-none-text">{escortSnatchOrderStatus === null ? '您还没接过接单哦～' : '暂无订单数据'}</Text>
                  {escortSnatchOrderStatus === null && (
                    <View
                      className="orders-btn"
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.navigateTo({
                          url: '/pages/package-D/pickupExpressDelivery/index',
                        });
                      }}
                    >
                      去接单
                    </View>
                  )}
                </>
              )}
            </View>
          )}
        </ScrollView>
        {/* 客服 */}
        <Image
          className="kf"
          src={kf}
          mode="widthFix"
          onClick={() => {
            this.kfClick();
          }}
        />

        {/* 请选择支付方式 */}
        <AtActionSheet
          isOpened={payModel}
          onClose={() => {
            action.commonChange('main.payModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.payModel', false);
          }}
        >
          <View className="payModel">
            <View className="row-box">
              <Text className="title">请选择支付方式</Text>
              <Image
                className="close"
                src={close}
                mode="widthFix"
                onClick={(e) => {
                  action.commonChange('main.payModel', false);
                }}
              />
            </View>
            <View className="model-price">
              <Text style={{ fontSize: 14, color: '#333333', fontWeight: 'bold' }}>¥</Text>
              <Text className="price">{price}</Text>
            </View>
            <Text className="integral-label">积分已抵扣2.30元</Text>
            <View className="btn-list">
              <View
                className={paySelected === 0 ? 'itemBox-a' : 'itemBox'}
                style={{ marginRight: '10px' }}
                onClick={(e) => {
                  this.setState({ paySelected: 0 });
                }}
              >
                <View className={paySelected === 0 ? 'item-a' : 'item'}>微信支付</View>
              </View>
              <View
                className={paySelected === 1 ? 'itemBox-a' : 'itemBox'}
                style={{ marginLeft: '10px' }}
                onClick={(e) => {
                  this.setState({ paySelected: 1 });
                }}
              >
                <View className={paySelected === 1 ? 'item-a' : 'item'}>钱包支付</View>
                <View className={paySelected === 1 ? 'balance-a' : 'balance'}>可用余额 ¥{accountBalanceTotal}</View>
              </View>
            </View>
            <View className="bottomBtn">付款 ¥{price}</View>
          </View>
        </AtActionSheet>

        {/* 请选择取消原因 */}
        <AtActionSheet
          isOpened={cancelModel}
          onClose={() => {
            action.commonChange('main.cancelModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.cancelModel', false);
          }}
        >
          <View className="cancelModel">
            <View className="row-box">
              <Text className="title">请选择取消原因</Text>
              <Image
                className="close"
                src={close}
                mode="widthFix"
                onClick={(e) => {
                  action.commonChange('main.cancelModel', false);
                }}
              />
            </View>
            <View className="list-box">
              {list.map((item, index) => {
                return (
                  <View
                    className="row"
                    key={index}
                    onClick={(e) => {
                      action.commonChange('main.cancellationReason', '');
                      action.commonChange('main.cancellationOptions', index);
                    }}>
                    <Text className="label">{item.label}</Text>
                    <Image className="check" src={cancellationOptions == index ? checkedIcon : checkIcon} mode="widthFix" />
                  </View>
                );
              })}
              {cancellationOptions == 3 && (
                <AtTextarea
                  className="textarea"
                  value={cancellationReason}
                  onChange={(e) => {
                    action.commonChange('main.cancellationReason', e?.substring?.(0, 300));
                  }}
                  maxLength={300}
                  placeholder="请输入取消原因(选填)"
                  placeholderStyle="color:#BFBFBF;font-size:14px"
                />
              )}
            </View>
            <View
              className="bottomBtn"
              onClick={(e) => {
                action.cancelEscorttrade();
              }}
            >
              确认取消
            </View>
          </View>
        </AtActionSheet>

        {/* 确认完成 */}
        <AtModal isOpened={confirmModel} className="confirmModel">
          <AtModalHeader>请输入收货码</AtModalHeader>
          <AtModalContent>
            <ReceivingCodeInput
              style={{ alignItems: 'center' }}
              focus={false}
              value={harvestCode}
              toPay={(val) => {
                action.commonChange('main.harvestCode', val);
              }}
            />
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                action.commonChange('main.confirmModel', false);
                action.commonChange('main.harvestCode', '');
              }}
            >
              取消
            </Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                if (harvestCode) {
                  action.commonChange('main.confirmModel', false);
                  action.harvestCode();
                } else {
                  Taro.showToast({
                    title: '请先输入收货码',
                    icon: 'none',
                    duration: 2000,
                  });
                }
              }}
            >
              确定
            </Button>
          </AtModalAction>
        </AtModal>
      </View>
    );
  }
}
